package com.yunduansing.core.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yunduansing.core.commons.DbCommon;
import com.yunduansing.core.commons.DbCommon.Grid;
import com.yunduansing.core.dao.RoleDao;
import com.yunduansing.core.model.RoleMenuModel;
import com.yunduansing.core.model.RoleModel;
import com.yunduansing.core.service.RoleService;
import com.yunduansing.core.utils.ResultUtil;

@Service
public class RoleServiceImpl implements RoleService {
	@Autowired
	private RoleDao dao;

	public RoleModel getByKey(Object key) {
		return dao.getByKey(key);
	}

	public ResultUtil save(RoleModel entity) {
		try{
			if(entity.getId()>0)
				return ResultUtil.init(dao.update(entity)>0);
			else{
				return ResultUtil.init(dao.add(entity)>0);
			}
		}catch(Exception e){
			return ResultUtil.init(e);
		}
	}

	public ResultUtil deleteByKeys(List<Object> keys) {
		try{
			return ResultUtil.init(dao.deleteByKeys(keys)>0);
		}catch(Exception e){
			return ResultUtil.init(e);
		}
	}

	public Object pagination(Grid grid, Object search) {
		DbCommon.Pager pager=new DbCommon.Pager();
		pager.setIndex(grid.getIndex());
		pager.setData(dao.pagination(grid, search));
		pager.setRows(dao.pageCount(search));
		return pager;
	}

	public ResultUtil setRoleMenuWithButtons(List<RoleMenuModel> list) {
		try{
			dao.deleteRoleMenuButtons(list.get(0).getRoleId());
			
			return ResultUtil.init();
		}catch(Exception e){
			return ResultUtil.init(e);
		}
	}

	@Transactional
	public ResultUtil saveRoleAndRoleMenuButtons(RoleModel model, List<RoleMenuModel> list) {
		try{
			if(model.getId()>0){
				dao.update(model);
				if(list.size()>0){
					dao.deleteRoleMenuButtons(list.get(0).getRoleId());
					dao.addRoleMenuButtons(list);
				}
			}else{
				dao.add(model);
				int roleId=model.getId();
				if(list.size()>0){
					for(RoleMenuModel item:list){
						item.setRoleId(roleId);
					}
					dao.addRoleMenuButtons(list);
				}
			}
			return ResultUtil.init();
		}catch(Exception e){
			//抛出异常，否则事务不起作用
			throw new RuntimeException(e.getMessage());
		}
	}

	public String getButtonCodeByMenuUrl(List<Integer> roleIds, String menuUrl) {
		List<String> btns=new ArrayList<String>();
		List<String> src=dao.getButtonCodeByMenuUrl(roleIds, menuUrl);
		System.out.println(src.size());
		for(String item:src){
			if(item!=null&&item.length()>0){
				String[] b=item.split(",");
				for(int i=0;i<b.length;i++){
					if(!btns.contains(b[i]))
						btns.add(b[i]);
				}
			}
		}
		return String.join(",", btns);
	}

	public List<RoleModel> getAll() {
		return dao.getAll();
	}
}
